package local.pt.iscte.dcti.pa.controller;

import java.util.Observable;
import java.util.Observer;

import local.pt.iscte.dcti.pa.model.WorksheetModel;
import local.pt.iscte.dcti.pa.view.*;

/**
 * Defines the controller
 * @author Simão Fernandes
 * @version %I%, %G%
 * @since 1.0
 */
public class WorksheetController implements Observer {
	private WorksheetView theView;
	private WorksheetModel theModel;
	
	/**
	 * Class constructor
	 * @param theView Reference to the view
	 * @param theModel Reference to the model
	 */
	public WorksheetController(WorksheetView theView, WorksheetModel theModel) {
		this.theView = theView;
		this.theModel = theModel;

		this.theView.addObserver(this);
		this.theModel.addObserver(this.theView.getMatriz());
	}
	
	/**
	 * Handles the changing of the observed instance
	 * @param o Reference to the observed instance
	 * @param arg Observed instance arguments
	 */
	@Override
	public void update(Observable o, Object arg) {
		
		VisibleElement ve = (VisibleElement)o;		
		int xx, yy;		
		String value;
		
		try {

			xx = ve.getXX();
			yy = ve.getYY();			
			
			
			String newValue;
			if (arg != null && ((boolean)arg)) {
				newValue = theModel.getCellValue(xx, yy);
			}
			else {
				value = ve.getValue();
				newValue = theModel.work(xx, yy, value);
			}
		}

		catch (NumberFormatException ex) {

			System.out.println(ex);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
}
